import datetime
import json
import os
import sys
import traceback
import pandas as pd
import uiautomation as auto
import re
import time
import pyautogui as pg
import pyperclip as pc
# from qingyunke.Message import reply_message
from cfg import *
from until.RegPattern import match_string, match_text, PATTERN_ISOLATED_NUMBER, PATTERN_KOU_FOLLOWING_RANGE
from until.auth.auth import auth_software
from until.sendMail import SendMail
from until.tool import findText


class WxRot:
    def __init__(self):
        self.count = 0

        self.wechat_win = auto.WindowControl(Name="微信", ClassName="WeChatMainWndForPC")
        self.shoukuanWin = self.wechat_win.ListControl(Name="会话")
        pd.set_option('mode.chained_assignment', None)
        # 操作间隔为1秒
        self.enter = enter  # 回车符
        self.index = 0
        pg.PAUSE = 1
        pg.FAILSAFE = False
        self.notification_history = {}  # 历史消息
        self.on_off_state = on_off_state  # 开关机状态
        self.msg_queue = {}
        self.robot_name = f'{robot_name}\u2005'  # 群聊机器人昵称

    def check_wx_window(self):
        pg.hotkey('ctrl', 'alt', 'w')
        # 最小化当前活动窗口
        pg.hotkey('winleft', 'down')

    # 找到群聊
    def open_group_chat(self):
        # pg.hotkey('ctrl', 'alt','w')
        pg.hotkey('ctrl', 'f')
        pc.copy(self.input_control_name)
        pg.hotkey('ctrl', 'v')
        pg.press('enter')

    def laod_config(self):
        with open('conf/config.json', 'r', encoding='utf-8') as f:
            data = json.loads(f.read())
            # data['reminders'] = ''.join(reminders)
            data['reminders'] = '@所有人 '
            return data

    # 发送微信消息
    def send_msg(self, msg, recipient):
        '''
        :param msg: 需发送的消息
        :param recipient: 消息发给谁
        :return:
        '''
        try:
            control_name = recipient if hasattr(self, 'input_control_name') else recipient
            # 加载群聊配置
            hour = time.localtime()
            now_time = time.strftime("%H:%M:%S", hour)
            # pg.hotkey('ctrl', 'alt', 'w')
            search_control = self.wechat_win.EditControl(Name='搜索')
            search_control.Click()
            search_control.SendKeys(recipient)
            time.sleep(1)

            pg.press('enter')
            # 自动适配群聊和好友

            pc.copy(msg)
            pg.hotkey('ctrl', 'v')
            # sendButton = self.wechat_win.ButtonControl(Name='发送(S)')
            # sendButton.Click()
            pg.press('enter')

        except Exception as e2:
            print(e2)

    def check_wechat_messages(self):
        try:
            # 获取微信窗口
            bbb = self.shoukuanWin.GetChildren()
            for chatMsg in bbb:

                if "条新消息" in chatMsg.Name:
                    # 点击最新的会话
                    # self.shoukuanWin.GetChildren()[0].Click()
                    #
                    print(chatMsg.Name)
                    self.input_control_name = re.sub('\d条新消息', '', chatMsg.Name)
                    # 获取消息列表控件
                    xiaoxis = self.wechat_win.ListControl(Name="消息")

                    s_time = time.time()
                    # pg.hotkey('ctrl', 'alt', 'w')
                    # pg.hotkey('winleft', 'down')
                    e_time = time.time()

                    # 获取消息列表控件的子控件
                    xiaoxi_children = xiaoxis.GetChildren()
                    # print(xiaoxi_children)
                    # 获取最后一个子控件
                    self.last_xiaoxi = xiaoxi_children[-1]

                    # 打印最后一条消息的内容
                    # 如果机器人被艾特回复内容含有入园，则给员工办理入员

                    self.at = f'@{self.robot_name}'
                    cur_msg = self.last_xiaoxi.Name
                    found_chars = [char for char in cur_msg if char in specified_chars]
                    res_found_chars = ''.join(found_chars)

                    edit = self.wechat_win.GetChildren()[-1].GetChildren()[-1].GetChildren()[-1].EditControl(
                        Name=self.input_control_name)  # .GetChildren()
                    match = bool(re.search('几个|第几|是什么字|在几', cur_msg))
                    isolated_number = re.search(PATTERN_ISOLATED_NUMBER, cur_msg)
                    pattern_kou_following_range = re.search(PATTERN_KOU_FOLLOWING_RANGE, cur_msg)
                    isolated_number_match = None
                    pattern_kou_following_range_match = None
                    if isolated_number:
                        isolated_number_match = isolated_number.group(1)
                        edit.SendKeys(f'{isolated_number_match}' + '{Enter}')
                        edit.Click()
                    elif pattern_kou_following_range:
                        pattern_kou_following_range_match = pattern_kou_following_range.group(1)
                        edit.SendKeys(f'{pattern_kou_following_range_match}' + '{Enter}')
                        edit.Click()
                    elif match:
                        res = match_text(cur_msg)
                        if res is not None:
                            edit.SendKeys(f'{res}' + '{Enter}')
                            edit.Click()
                    elif cur_msg.__contains__('扣'):
                        self.count += 1
                        res = findText(cur_msg)
                        if res is not None:
                            edit.SendKeys(f'{res}' + '{Enter}')
                            edit.Click()
                    elif len(found_chars) <= 1 and self.at in cur_msg and self.count <= 6 and len(
                            cur_msg) > 3 and cur_msg.__contains__('扣'):

                        self.count += 1
                        edit.SendKeys(f'{res_found_chars}' + '{Enter}')
                        edit.Click()

                        self.index += 1

                    elif len(found_chars) <= 1 and self.count <= 6 and len(cur_msg) > 3 and cur_msg.__contains__('扣'):
                        edit.SendKeys(f'{res_found_chars}' + '{Enter}')
                        edit.Click()

                        self.index += 1
                    elif self.count > 6:
                        mail = SendMail()
                        mail.set_mail_content(f'程序扣到了：{self.count}个')
                        mail.send_mail()
                    print(f'\rdate：{datetime.datetime.now()} {self.input_control_name}：{cur_msg} {res_found_chars}',
                          end='')

                    print(
                    f"\r{self.input_control_name}：{self.last_xiaoxi.Name} 已扣次数：{self.count} \t耗时：{e_time - s_time} ",
                    end='')

                # chatMsg.Click()

        except Exception as e:
            print('error', e)
            mail = SendMail()
            mail.set_mail_content(f'程序异常：{e}')
            # mail.send_mail()

    def exec(self):
        # self.check_wx_window()
        self.cf = self.laod_config()
        try:
            while True:
                self.check_wechat_messages()
                time.sleep(1)
        except KeyboardInterrupt:
            print("程序退出~")
        except Exception as e:
            print(f"程序执行出现了问题: {str(e)}")


if __name__ == "__main__":
    # auth = auth_software()
    if True:
        wx = WxRot()
        wx.exec()
